package com.yingpai.fitness.dvp_2_0.main.activity.vip;

import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.adapter.BaseAdapterHelper;
import com.yingpai.fitness.dvp_2_0.common.adapter.QuickAdapter;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.DateFormatUtil;
import com.yingpai.fitness.dvp_2_0.common.util.SharedPreferencesHelp;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.main.activity.fitness.StoreActivity;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.entity.vip_card.MemberInfoBean;
import com.yingpai.fitness.entity.vip_card.NotVipListBean;
import com.yingpai.fitness.entity.wx.TokenBean;
import com.yingpai.fitness.dvp_2_0.common.view.XListView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by ASUS on 2018/11/12.
 */

public class VipCardActivity extends CommonActivity {
    @BindView(R.id.user_photo)
    CircleImageView userPhoto;
    @BindView(R.id.user_name)
    TextView userName;
    @BindView(R.id.qr_code)
    ImageView qrCode;
    @BindView(R.id.remaining_time)
    TextView remainingTime;
    @BindView(R.id.listview)
    XListView listview;
    @BindView(R.id.nested_scroll_view)
    NestedScrollView nestedScrollView;
    @BindView(R.id.title_bar)
    RelativeLayout titleBar;
    @BindView(R.id.vip_rl)
    RelativeLayout vipRl;
    @BindView(R.id.renew)
    Button renew;
    private TokenBean tokenBean;
    private QuickAdapter<NotVipListBean.MapData.VipCardListData> quickAdapter;
    private MemberInfoBean mMemberInfo;
    private JSONObject jsonObject;
    private DecimalFormat df = new DecimalFormat("######.###");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusFlag(Contacts.NORMAL_STATUS);
        setContentView(R.layout.activity_vip_card);
    }

    @Override
    protected void initData() {
        showDialog(this, null);
        HttpParams httpParams = new HttpParams();
        if(tokenBean == null || tokenBean.getId() == 0){
            return;
        }
        httpParams.put("customerId", tokenBean.getId());
        finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.GET_INFORMATION, httpParams, Url.GET_INFORMATION, new Callback<MemberInfoBean>() {
            @Override
            public void onSuccess(MemberInfoBean memberInfoBean) {
                dismissDialog();
                mMemberInfo = memberInfoBean;
                if (Constant.REQUEST_SUCCESS.equals(mMemberInfo.getResult())) {
                    if(memberInfoBean.getMap().getCustomer().isIsMemeber()){
                        renew.setVisibility(View.VISIBLE);
                    }else{
                        renew.setVisibility(View.GONE);
                    }
                    userName.setText(mMemberInfo.getMap().getCustomer().getNickName() + "");
                    Glide.with(VipCardActivity.this)
                            .load(mMemberInfo.getMap().getCustomer().getPhotoUrl())
                            .error(R.mipmap.icon_user_default)
                            .centerCrop()
                            .into(userPhoto);
                    qrCode.setVisibility(View.VISIBLE);
                    if(mMemberInfo.getMap().getCustomer().getExpireDate()==null){
                        remainingTime.setVisibility(View.GONE);
                    }else{
                        remainingTime.setVisibility(View.VISIBLE);
                        remainingTime.setText("会员到期日期:" + mMemberInfo.getMap().getCustomer().getExpireDate());
                    }
                    jsonObject = new JSONObject();
                    try {
                        jsonObject.put("customerId", tokenBean.getId());
                        jsonObject.put("createTime", DateFormatUtil.getTodaydate());
                        jsonObject.put("activeTime", 10);
                        jsonObject.put("QRCodeId", mMemberInfo.getMap().getQRCodeId());
                        jsonObject.put("expireDate", mMemberInfo.getMap().getCustomer().getExpireDate());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    qrCode.post(new Runnable() {
                        @Override
                        public void run() {
                            qrCode.setImageBitmap(CodeUtils.createImage(jsonObject.toString(), qrCode.getWidth(), qrCode.getWidth(), BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)));
                        }
                    });
                    if (mMemberInfo.getMap().getCustomer().isIsMemeber()) {
                        NotVipListBean notVipListBean = new NotVipListBean();
                        notVipListBean.setMap(new NotVipListBean.MapData());
                        notVipListBean.getMap().setVipCardList(new ArrayList<NotVipListBean.MapData.VipCardListData>());
                        notVipListBean.getMap().getVipCardList().add(new NotVipListBean.MapData.VipCardListData());
                        notVipListBean.getMap().getVipCardList().get(0).setCard_name("私教课/操课");
                        notVipListBean.getMap().getVipCardList().get(0).setCard_photo("");
                        quickAdapter.clear();
                        quickAdapter.addAll(notVipListBean.getMap().getVipCardList());
                        quickAdapter.notifyDataSetChanged();

                    } else {
                        finalOkGo.request(RequestType.GET, Contacts.HOST_SERVER + Url.GET_VIP_CARD, null, Url.GET_VIP_CARD, new Callback<NotVipListBean>() {
                            @Override
                            public void onSuccess(NotVipListBean notVipListBean) {
                                if (Constant.REQUEST_SUCCESS.equals(notVipListBean.getResult())) {
                                    quickAdapter.clear();
                                    quickAdapter.addAll(notVipListBean.getMap().getVipCardList());
                                    quickAdapter.notifyDataSetChanged();
                                } else {
                                    showToast(notVipListBean.getMsg());
                                }
                            }
                        });
                    }
                } else {
                    showToast(mMemberInfo.getMsg());
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    protected void initView() {
        setTitle("会员卡");
        EventBus.getDefault().register(this);
        tokenBean = (TokenBean) SharedPreferencesHelp.getBean(Constant.TOKENBEAN);

        final int startColor = ContextCompat.getColor(this, R.color.normal_status);
        final int endColor = ContextCompat.getColor(this, R.color.colorNavigation);

        nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                int headHeight = vipRl.getHeight();
                int scrollDistance = Math.min(scrollY, headHeight);
                float fraction = (float) scrollDistance / (float) headHeight;

//                setToolbarStatusBarAlpha(evaluate(fraction, startColor, endColor),titleBar);
                setNavigationViewColor(evaluate(fraction, startColor, endColor));
            }
        });

        quickAdapter = new QuickAdapter<NotVipListBean.MapData.VipCardListData>(this, R.layout.vip_card_list_item) {
            @Override
            protected void convert(BaseAdapterHelper helper, NotVipListBean.MapData.VipCardListData item) {
                ImageView photo = helper.getView(R.id.vip_card_cover_iv);
                if (!"".equals(item.getCard_photo())) {
                    if (!item.getCard_photo().contains(",")) {
                        Glide.with(context)
                                .load(item.getCard_photo())
                                .error(R.mipmap.vip_card_pic_new)
                                .into(photo);
                    } else {
                        Glide.with(context)
                                .load(item.getCard_photo().substring(0, item.getCard_photo().indexOf(",")))
                                .error(R.mipmap.vip_card_pic_new)
                                .into(photo);
                    }
                }

                helper.setText(R.id.vip_card_course_class_type, item.getCard_name());
                TextView vipCardCurseLimitTv = helper.getView(R.id.vip_card_course_limit_tv);
                TextView vipCardCoursePrice = helper.getView(R.id.vip_card_course_price);
                if (mMemberInfo.getMap().getCustomer().isIsMemeber()) {
                    vipCardCurseLimitTv.setVisibility(View.INVISIBLE);
                    vipCardCoursePrice.setVisibility(View.INVISIBLE);
                } else {
                    vipCardCurseLimitTv.setVisibility(View.VISIBLE);
                    vipCardCoursePrice.setVisibility(View.VISIBLE);
                    vipCardCurseLimitTv.setText(item.getCard_info());
                    vipCardCoursePrice.setText("￥" + df.format(item.getCard_price() / 100));
                }

            }
        };
        listview.setAdapter(quickAdapter);

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mMemberInfo.getMap().getCustomer().isIsMemeber()) {
                    startActivity(StoreActivity.class);
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("vipInfo", quickAdapter.getItem(position));
                    bundle.putSerializable("infomation", mMemberInfo);
                    startActivity(BuyVipCardActivity.class, bundle);
                }
            }
        });
    }

    @Override
    @OnClick({R.id.qr_code,R.id.renew})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.qr_code:
                Bundle bundle = new Bundle();
                bundle.putString("qr_data", jsonObject.toString());
                startActivity(QR_Activity.class, bundle);
                break;
            case R.id.renew:
                startActivity(VipRenewActivity.class);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(String event) {
        if (Constant.REQUEST_SUCCESS.equals(event)) {
            initData();
        }
    }
}
